using System;
using FireStarterModeller.BO;
using Habanero.Base.Exceptions;

namespace FireStarterModeller.Logic.Commands
{
    public class CreateAssemblyCommand : ICommand
    {
        private readonly DMSolution _solution;
        private readonly string _assemblyName;

        public CreateAssemblyCommand(DMSolution solution, string assemblyName)
        {
            _solution = solution;
            _assemblyName = assemblyName;
        }

        public void Apply()
        {
            DMAssembly assembly = _solution.CreateAssembly(_assemblyName);
            try
            {
                assembly.Save();
            } catch (Exception)
            {
                _solution.Assemblies.Remove(assembly);
                throw;
            }
        }

        public void Revert()
        {
            DMAssembly assembly = _solution.Assemblies.Find(info => info.AssemblyName == _assemblyName);
            if (assembly == null)
            {
                string message = string.Format("Error reverting change. Assembly with the name '{0}' not found to remove from solution '{1}'.", _assemblyName, _solution.SolutionName);
                throw new HabaneroDeveloperException(message, "");
            }
            assembly.MarkForDelete();
            assembly.Save();
        }
    }
}